extends CharacterBody2D

@export var move_speed: float = 70
@export var animator: AnimatedSprite2D

var is_game_over: bool = false

@export var bullet_scene : PackedScene

@export var joypad : Sprite2D

func _process(delta: float) -> void:	
	if velocity == Vector2.ZERO or is_game_over:
		$RunningSound.stop()
	elif not $RunningSound.playing:
		$RunningSound.play()


func _physics_process(delta: float) -> void:
	if not is_game_over:
		# 设置移动向量和速度
		# velocity = Input.get_vector("左","右","上","下") * move_speed
		velocity = joypad.get_now_pos() * move_speed
		if velocity == Vector2.ZERO:
			animator.play("idle")
		else:
			animator.play("run")
		move_and_slide()
	
func game_over():
	if not is_game_over:
		is_game_over = true
		animator.play("game_over")
		$GameOverSound.play()
		get_tree().current_scene.show_game_over()
		# 等待3秒，游戲重啓
		await get_tree().create_timer(3).timeout
		get_tree().reload_current_scene()
	

func _on_fire() -> void:
	if velocity != Vector2.ZERO or is_game_over:
		return
	# 新建一個子彈節點
	var bullet_node = bullet_scene.instantiate()
	# 設置子彈位置為當前玩家位置
	bullet_node.position = position + Vector2(12,6)
	# 將子彈場景添加到當前場景
	get_tree().current_scene.add_child(bullet_node)
	$FireSound.play()
	
func _input(event: InputEvent) -> void:
	if event is InputEventScreenTouch and event.is_pressed():
		joypad.visible = true
		joypad.position = event.position
	if event is InputEventScreenTouch and !event.is_pressed():
		joypad.visible = false
